package com.hengtiansoft.lfy.activity;

import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.reflect.TypeToken;
import com.hengtiansoft.lfy.R;
import com.hengtiansoft.lfy.base.BaseActivity;
import com.hengtiansoft.lfy.chart.DemoHXSDKHelper;
import com.hengtiansoft.lfy.chart.action.ContactListJson;
import com.hengtiansoft.lfy.chart.action.GetUserJson;
import com.hengtiansoft.lfy.chart.activity.ChatActivity;
import com.hengtiansoft.lfy.chart.bean.ThirdLogin;
import com.hengtiansoft.lfy.chart.fragment.ChatAllHistoryFragment;
import com.hengtiansoft.lfy.chart.activity.NewFriendsMsgActivity;
import com.hengtiansoft.lfy.chart.applib.controller.HXSDKHelper;
import com.hengtiansoft.lfy.chart.applib.utils.HXPreferenceUtils;
import com.hengtiansoft.lfy.chart.bean.BaseResult;
import com.hengtiansoft.lfy.chart.bean.Friends;
import com.hengtiansoft.lfy.chart.bean.getUserByUsernameBean;
import com.hengtiansoft.lfy.chart.db.InviteMessgeDao;
import com.hengtiansoft.lfy.chart.db.UserDao;
import com.hengtiansoft.lfy.chart.domain.FriendsUser;
import com.hengtiansoft.lfy.chart.domain.InviteMessage;
import com.hengtiansoft.lfy.chart.net.JsonListRequest;
import com.hengtiansoft.lfy.chart.net.VolleyUtil;
import com.hengtiansoft.lfy.constants.Constants;
import com.hengtiansoft.lfy.entity.RequestRegister;
import com.hengtiansoft.lfy.entity.ServiceResult;
import com.hengtiansoft.lfy.entity.TokenInfo;
import com.hengtiansoft.lfy.net.NetHelper;
import com.hengtiansoft.lfy.net.NetUtils;
import com.hengtiansoft.lfy.utils.CommonUtils;
import com.hengtiansoft.lfy.utils.Config;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMContactListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.util.HanziToPinyin;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.hengtiansoft.lfy.activity.MyInformationActivity.setObject;


/**
 * Created by daiye on 2016/10/27 0027.
 */

public class LoginActivityV2 extends BaseActivity {
    private boolean isRegisterOtherUser = false;
    private static final String TAG = LoginActivityV2.class.getSimpleName();
    private final int ACTIVITY_RESULT_REGISTER = 1;
    private final int ACTIVITY_RESULT_FORGET_PASSWORD = 2;
    private TextView mTvSkip;
    private EditText mUserNameEt;
    private EditText mPasswordEt;
    private Button mLoginBt;
    private TextView mRegisterTv;
    private TextView mForgetPasswordTv;

    private ImageView mWeixinIb;
    private ImageView mWeiboIb;
    private ImageView mQQIb;
    private boolean progressShow;
    private int third_login=0;
  //  private String userNameStr="";
   // private String passwordStr="";
    private ProgressDialog pd;
    // 整个平台的UMShareAPI,负责管理整个SDK的配置、操作等处理
    private UMShareAPI mShareAPI;
    private Context mContext;
    private String currentUsername;
    private String currentPassword;
    private UserDao userDao;
    private InviteMessgeDao inviteMessgeDao;
    NotificationCompat.Builder mBuilder;
    public NotificationManager mNotificationManager;
    private boolean updatenick;
    private String from = "";
    private boolean hasGetTokenJson = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        from=getIntent().getStringExtra("from");
        mContext = this;
        initData();
        initView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void initData(){

    }

    private void initView() {
        setContentView(R.layout.activity_login);
        pd = new ProgressDialog(LoginActivityV2.this,
                ProgressDialog.THEME_HOLO_LIGHT);
        pd.setCanceledOnTouchOutside(false);
        pd.setOnCancelListener(new DialogInterface.OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                progressShow = false;
            }
        });
        inviteMessgeDao = new InviteMessgeDao(this);
        userDao = new UserDao(this);
        mNotificationManager = (NotificationManager) getSystemService(
                NOTIFICATION_SERVICE);
        mTvSkip =  (TextView) findViewById(R.id.tv_skip);
        mTvSkip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mUserNameEt = (EditText) findViewById(R.id.username_et);
        mPasswordEt = (EditText) findViewById(R.id.password_et);
        mLoginBt = (Button) findViewById(R.id.login_bt);
        mRegisterTv = (TextView)findViewById(R.id.register_tv);
        mForgetPasswordTv = (TextView)findViewById(R.id.forget_password_tv);

        mLoginBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InputMethodManager inputManager = (InputMethodManager) mLoginBt.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.showSoftInput(mLoginBt, 0);
                processLogin();
            }
        });
        mRegisterTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InputMethodManager inputManager = (InputMethodManager) mLoginBt.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.showSoftInput(mLoginBt, 0);
                Intent intent = new Intent(LoginActivityV2.this, RegisterActivityV2.class);
                startActivityForResult(intent, ACTIVITY_RESULT_REGISTER);
                finish();
            }
        });
        mForgetPasswordTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InputMethodManager inputManager = (InputMethodManager) mLoginBt.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.showSoftInput(mLoginBt, 0);
                Intent intent = new Intent(LoginActivityV2.this, PasswordForgetActivityV2.class);
                startActivityForResult(intent, ACTIVITY_RESULT_FORGET_PASSWORD);
            }
        });

        mWeixinIb = (ImageView) findViewById(R.id.iv_login_weixin);
        mWeiboIb = (ImageView) findViewById(R.id.iv_login_weibo);
        mQQIb = (ImageView) findViewById(R.id.iv_login_qq);

        mShareAPI = UMShareAPI.get(this);

        mWeixinIb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                third_login = 1;
                login(SHARE_MEDIA.WEIXIN);
            }
        });
        mWeiboIb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                third_login = 2;
                login(SHARE_MEDIA.SINA);
            }
        });
        mQQIb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                third_login = 3;
                login(SHARE_MEDIA.QQ);
            }
        });

        mPasswordEt.setTypeface(Typeface.DEFAULT);
        mPasswordEt.setTransformationMethod(new PasswordTransformationMethod());

        if(Config.isUserLogined()){
            mUserNameEt.setText(Config.getUserName());
        }
    }

    /**
     * 登录自己服务器
     *
     * @param
     */
    private void processLogin(){
            currentUsername= mUserNameEt.getText().toString();
            if(TextUtils.isEmpty(currentUsername) ){
                Toast.makeText(this, R.string.login_username_empty_tips, Toast.LENGTH_SHORT).show();
                return;
            }
            if(TextUtils.isEmpty(mPasswordEt.getText().toString()) ){
                Toast.makeText(this, R.string.login_password_empty_tips, Toast.LENGTH_SHORT).show();
                return;
            }
        currentPassword= CommonUtils.MD5(mPasswordEt.getText().toString().trim());
        if(!hasGetTokenJson){
            getUserToken();
        }

    }

    /***
     * 登陆环信聊天
     */
    public void loginChart(){
        progressShow = true;
        // 登陆成功，保存用户名密码
        Config.setUserName(currentUsername);
        Config.setPassword(currentPassword);
        // 调用sdk登陆方法登陆聊天服务器
        EMClient.getInstance().login(currentUsername, currentPassword,
                new EMCallBack() {

                    @Override
                    public void onSuccess() {
                        Config.setUserName(currentUsername);
                        Config.setPassword(currentPassword);
                        try {
                            // ** 第一次登录或者之前logout后再登录，加载所有本地群和回话
                            // ** manually load all local groups and
                            EMClient.getInstance().groupManager().loadAllGroups();
                            EMClient.getInstance().chatManager().loadAllConversations();
                            // 处理好友和群组
                            initializeContacts();
                        } catch (Exception e) {
                            e.printStackTrace();
                            // 取好友或者群聊失败，不让进入主页面
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    pd.dismiss();
                                    DemoHXSDKHelper.getInstance().logout(true, //退出登陆
                                            null);
                                        Config.setUserToken(null);//清空token
                                    // 登录失败: 获取好友或群聊失败
                                    Toast.makeText(getApplicationContext(),
                                            R.string.login_failure_failed, 1)
                                            .show();
                                }
                            });
                            return;
                        }
                        GetUserJson getUserJson = new GetUserJson(Config.getUserToken(),
                                currentUsername);
                        getUserByUsernameRequest(Constants.getUserByUsername,
                                getUserJson);
                    }

                    @Override
                    public void onProgress(int progress, String status) {
                    }

                    @Override
                    public void onError(final int code, final String message) {
                        Config.setUserName(null);
                        Config.setPassword(null);
                        if (!progressShow) {
                            return;
                        }
                        runOnUiThread(new Runnable() {
                            public void run() {
                                pd.dismiss();
                                Toast.makeText(getApplicationContext(),
                                        getString(R.string.loginfail), Toast.LENGTH_SHORT)
                                        .show();
                            }
                        });
                    }
                });
    }
    /**
     * 从服务器获取登录者的相关信息
     *
     * @param getUserByUsername
     * @param mGetUserJson
     */
    private void getUserByUsernameRequest(String getUserByUsername,
                                          GetUserJson mGetUserJson) {
        Log.i(TAG,
                "<getUserByUsernameRequest>--<onResponse>--上传的JSon数据：  GetUserJson = "
                        + mGetUserJson);
        Type type = new TypeToken<BaseResult<getUserByUsernameBean>>() {
        }.getType();
        JsonListRequest<BaseResult<getUserByUsernameBean>> request = new JsonListRequest<BaseResult<getUserByUsernameBean>>(
                mContext, Request.Method.POST, getUserByUsername,
                mGetUserJson.toString(), null, null, type, false,
                new Response.Listener<BaseResult<getUserByUsernameBean>>() {

                    @Override
                    public void onResponse(
                            BaseResult<getUserByUsernameBean> arg0) {
                        Log.i(TAG,
                                "<getUserByUsernameRequest>--<onResponse>--服务器返回的JSon数据：  arg0 = "
                                        + arg0);
                        int code = 1;
                        String message = null;
                        getUserByUsernameBean data = null;
                        message = arg0.getMessage();
                        code = arg0.getCode();
                        Log.i(TAG,
                                "<getUserByUsernameRequest>--<onResponse>--服务器返回的JSon数据：  message = "
                                        + message);
                        Log.i(TAG,
                                "<getUserByUsernameRequest>--<onResponse>--服务器返回的JSon数据：  code = "
                                        + code);
                        if (code == 0) {
                            data = arg0.getData();
                            if (data != null) {


                                HXPreferenceUtils.getInstance()
                                        .setCurrentUserAvatar(Constants.GETIMAGE
                                                + data.getImagepath());
                                HXPreferenceUtils.getInstance()
                                        .setCurrentUserSex(data.getSex());
                                if (null != data.getNickname()) {
                                    HXPreferenceUtils.getInstance()
                                            .setCurrentUserNick(
                                                    data.getNickname());
                                } else {
                                    HXPreferenceUtils.getInstance()
                                            .setCurrentUserNick(
                                                    data.getUsername());
                                }
                                HXPreferenceUtils.getInstance()
                                        .setCurrentUserSignature(
                                                data.getSignature());
                                HXPreferenceUtils.getInstance()
                                        .setCurrentUserBackground(
                                                Constants.GETIMAGE
                                                        + data.getBackphoto());
                                HXPreferenceUtils.getInstance()
                                        .setCurrentUserMobile(
                                                data.getTelphone());
                                HXPreferenceUtils.getInstance()
                                        .setCurrentUserThreeLogin(third_login);
                                // 更新当前用户的nickname 此方法的作用是在ios离线推送时能够显示用户nick
                                new Thread(new Runnable() {

                                    @Override
                                    public void run() {
                                        updatenick = EMClient.getInstance().pushManager()
                                                .updatePushNickname(
                                                        HXPreferenceUtils
                                                                .getInstance()
                                                                .getCurrentUserNick());
                                    }
                                }).start();
                                if (!updatenick) {
                                    Log.e("LoginActivity", HXPreferenceUtils
                                            .getInstance().getCurrentUserNick()
                                            + "----"
                                            + "update current user nick fail");
                                }
                                ContactListJson contactListJson = new ContactListJson(
                                       Config.getUserName(),
                                        Config.getUserToken());
                                getContactList(Constants.FRIENDSLIST,
                                        contactListJson);
                            }
                        } else {
                            Config.setUserToken(null);
                            DemoHXSDKHelper.getInstance().logout(true, null);
                            Toast.makeText(mContext, message, Toast.LENGTH_LONG)
                                    .show();
                            pd.dismiss();
                        }

                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError arg0) {
                NetworkResponse response = arg0.networkResponse;
                if (response != null) {
                    try {
                        String json = new String(response.data,
                                HttpHeaderParser.parseCharset(
                                        response.headers));
                        Log.i(TAG,
                                "<getUserByUsernameRequest>--<onErrorResponse> -- json = "
                                        + json);
                        Log.i(TAG,
                                "<getUserByUsernameRequest>--<onErrorResponse> -- response.data = "
                                        + response.data);
                        Log.i(TAG,
                                "<getUserByUsernameRequest>--<onErrorResponse> -- response.headers = "
                                        + response.headers);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
                if (arg0 != null && arg0.toString().contains(
                        "com.android.volley.NoConnectionError")) {
                    Toast.makeText(mContext,
                            getString(R.string.network_unavailable),
                            Toast.LENGTH_SHORT).show();
                } else if (arg0 != null && arg0.toString()
                        .contains("com.android.volley.ServerError")) {
                    Toast.makeText(mContext,
                            getString(
                                    R.string.service_temporarily_unavailable),
                            Toast.LENGTH_SHORT).show();
                } else if (arg0 != null && arg0.toString()
                        .contains("com.android.volley.TimeoutError")) {
                    Toast.makeText(mContext,
                            getString(R.string.time_out_error),
                            Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(mContext,
                            getString(R.string.request_fail),
                            Toast.LENGTH_SHORT).show();
                }
                Log.i(TAG,
                        "<getUserByUsernameRequest>--<onErrorResponse>--服务器请求失败： arg0 = "
                                + arg0);
                Log.i(TAG,
                        "<getUserByUsernameRequest>--<onErrorResponse>--服务器请求失败： response = "
                                + response);
                Config.setUserToken(null);
                DemoHXSDKHelper.getInstance().logout(true, null);
                pd.dismiss();
            }

        });
        VolleyUtil.addRequest(request);
    }
    /**
     * 获取好友列表
     *
     * @param getContactListUrl
     * @param mContactListJson
     */
    private void getContactList(String getContactListUrl,
                                ContactListJson mContactListJson) {
        Log.i(TAG, "<loginRequest>--<onResponse>--上传的JSon数据：  LoginJson = "
                + mContactListJson);
        java.lang.reflect.Type type = new TypeToken<BaseResult<List<Friends>>>() {
        }.getType();
        JsonListRequest<BaseResult<List<Friends>>> request = new JsonListRequest<BaseResult<List<Friends>>>(
                mContext, Request.Method.POST, getContactListUrl,
                mContactListJson.toString(), null, null, type, true,
                new Response.Listener<BaseResult<List<Friends>>>() {

                    @Override
                    public void onResponse(BaseResult<List<Friends>> arg0) {
                        Log.i(TAG,
                                "<loginRequest>--<onResponse>--服务器返回的JSon数据：  arg0 = "
                                        + arg0);
                        int code = 1;
                        String message = null;
                        List<Friends> data = null;
                        Friends friends = null;
                        message = arg0.getMessage();
                        code = arg0.getCode();
                        data = arg0.getData();
                        Log.i(TAG,
                                "<loginRequest>--<onResponse>--服务器返回的JSon数据：  message = "
                                        + message);
                        Log.i(TAG,
                                "<loginRequest>--<onResponse>--服务器返回的JSon数据：  code = "
                                        + code);
                        Log.i(TAG,
                                "<loginRequest>--<onResponse>--服务器返回的JSon数据：  data = "
                                        + data);
                        if (code == 0) {
                            // 登陆成功，保存用户名密码
                            if (null != data) {
                                Context context = HXSDKHelper.getInstance()
                                        .getAppContext();
                                Map<String, FriendsUser> userlist = new HashMap<String, FriendsUser>();
                                // 添加user"申请与通知"
                                FriendsUser newFriends = new FriendsUser(Constants.NEW_FRIENDS_USERNAME);
                                // newFriends.setUsername(
                                //        Constant.NEW_FRIENDS_USERNAME);
                                String strChat = context.getString(
                                        R.string.Application_and_notify);
                                newFriends.setNickname(strChat);

                                userlist.put(Constants.NEW_FRIENDS_USERNAME,
                                        newFriends);
                                // 添加"群聊"
                                FriendsUser groupUser = new FriendsUser(Constants.GROUP_USERNAME);
                                String strGroup = context
                                        .getString(R.string.group_chat);
                                //  groupUser.setUsername(Constant.GROUP_USERNAME);
                                groupUser.setNickname(strGroup);
                                groupUser.setHeader("");
                                userlist.put(Constants.GROUP_USERNAME,
                                        groupUser);
                                for (int i = 0; i < data.size(); i++) {
                                    String username = data.get(i)
                                            .getFusername();
                                    FriendsUser friendsUser = new FriendsUser(username);
                                    String nick = data.get(i).getFname();
                                    String avatar = Constants.GETIMAGE
                                            + data.get(i).getFimage();
                                    // friendsUser.setUsername(username);
                                    friendsUser.setNickname(nick);
                                    friendsUser.setAvatar(avatar);
                                    setUserHearder(username, friendsUser);
                                    userlist.put(username, friendsUser);
                                    if (nick != null && !nick.equals("")) {
                                        Log.i("nick", nick);
                                    }
                                }
                                // 存入内存
                                ((DemoHXSDKHelper) HXSDKHelper.getInstance())
                                        .setContactList(userlist);
                                // 存入db
                                UserDao dao = new UserDao(mContext);
                                List<FriendsUser> users = new ArrayList<FriendsUser>(
                                        userlist.values());
                                dao.saveContactList(users);
                                HXSDKHelper.getInstance()
                                        .notifyContactsSyncListener(true);

                                if (HXSDKHelper.getInstance()
                                        .isGroupsSyncedWithServer()) {
                                    HXSDKHelper.getInstance()
                                            .notifyForRecevingEvents();
                                }
                                ((DemoHXSDKHelper) HXSDKHelper.getInstance())
                                        .getUserProfileManager()
                                        .notifyContactInfosSyncListener(true);
                                HXSDKHelper.getInstance()
                                        .setisContactsSyncedWithServer();
                                if (!LoginActivityV2.this.isFinishing()
                                        && pd.isShowing()) {
                                    pd.dismiss();
                                }

                                // 进入主页面
                                if (null != from) {
//                                    if (from.equals("ChangeAvatar")) {
//                                        startActivity(new Intent(mContext,
//                                                MyInformationActivity.class));
//                                    } else if (from
//                                            .equals("toCollectionActivity")) {
//                                        startActivity(new Intent(mContext,
//                                                CollectionActivity.class));
//                                    } else if (from.equals("chat")) {
//                                        Intent intent = new Intent(
//                                                LoginActivityV2.this,
//                                                ChatAllHistoryFragment.class);
//                                        startActivity(intent);
//                                    } else if (from.equals("sence")) {
//                                        Intent intent = new Intent(
//                                                LoginActivityV2.this,
//                                                ChatAllHistoryFragment.class);
//                                        startActivity(intent);
//                                    } else
                                    if(from.equals("loginout")){
                                        startActivity(new Intent(mContext,
                                                MainActivity.class));
                                    }
                                } else {
//                                    startActivity(new Intent(mContext,
//                                            MainActivity.class));
                                }
                                finish();
                                Toast.makeText(mContext, getString(R.string.loginok),
                                        Toast.LENGTH_SHORT);
                                EMClient.getInstance().contactManager()
                                        .setContactListener(
                                                new MyContactListener());
                                // EMChat.getInstance().setAppInited();

                            }
                        } else {
                            pd.dismiss();
                            Config.setUserToken(null);
                            DemoHXSDKHelper.getInstance().logout(true, null);
                            Toast.makeText(mContext, message, Toast.LENGTH_LONG)
                                    .show();
                        }
                        // closeProgressDialog();
                        // hasSendJson = false;
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError arg0) {
                NetworkResponse response = arg0.networkResponse;
                if (response != null) {
                    try {
                        String json = new String(response.data,
                                HttpHeaderParser.parseCharset(
                                        response.headers));
                        Log.i(TAG,
                                "<loginRequest>--<onErrorResponse> -- json = "
                                        + json);
                        Log.i(TAG,
                                "<loginRequest>--<onErrorResponse> -- response.data = "
                                        + response.data);
                        Log.i(TAG,
                                "<loginRequest>--<onErrorResponse> -- response.headers = "
                                        + response.headers);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
                if (arg0 != null && arg0.toString().contains(
                        "com.android.volley.NoConnectionError")) {
                    Toast.makeText(mContext,
                            getString(R.string.network_unavailable),
                            Toast.LENGTH_SHORT).show();
                } else if (arg0 != null && arg0.toString()
                        .contains("com.android.volley.ServerError")) {
                    Toast.makeText(mContext,
                            getString(
                                    R.string.service_temporarily_unavailable),
                            Toast.LENGTH_SHORT).show();
                } else if (arg0 != null && arg0.toString()
                        .contains("com.android.volley.TimeoutError")) {
                    Toast.makeText(mContext,
                            getString(R.string.time_out_error),
                            Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(mContext,
                            getString(R.string.request_fail),
                            Toast.LENGTH_SHORT).show();
                }
                Log.i(TAG,
                        "<loginRequest>--<onErrorResponse>--服务器请求失败： arg0 = "
                                + arg0);
                Log.i(TAG,
                        "<loginRequest>--<onErrorResponse>--服务器请求失败： response = "
                                + response);
                Config.setUserToken(null);
                DemoHXSDKHelper.getInstance().logout(true, null);
                pd.dismiss();
            }

        });
        VolleyUtil.addRequest(request);
    }
    /**
     * 设置hearder属性，方便通讯中对联系人按header分类显示，以及通过右侧ABCD...字母栏快速定位联系人
     *
     * @param username
     * @param user
     */
    private static void setUserHearder(String username, FriendsUser user) {
        String headerName = null;
        if (!TextUtils.isEmpty(user.getNick())) {
            headerName = user.getNick();
        } else {
            headerName = user.getUsername();
        }
        if (username.equals(Constants.NEW_FRIENDS_USERNAME)) {
            user.setHeader("");
        } else if (Character.isDigit(headerName.charAt(0))) {
            user.setHeader("#");
        } else {
            user.setHeader(
                    HanziToPinyin.getInstance().get(headerName.substring(0, 1))
                            .get(0).target.substring(0, 1).toUpperCase());
            char header = user.getHeader().toLowerCase().charAt(0);
            if (header < 'a' || header > 'z') {
                user.setHeader("#");
            }
        }
    }
    /***
     * 好友变化listener
     *
     */
    public class MyContactListener implements EMContactListener {

        @Override
        public void onContactAdded(String username) {
            // 保存增加的联系人
            Map<String, FriendsUser> localUsers = ((DemoHXSDKHelper) HXSDKHelper
                    .getInstance()).getContactList();
            Map<String, FriendsUser> toAddUsers = new HashMap<String, FriendsUser>();
            //  for (String username : usernameList) {
            FriendsUser user = setUserHead(username);
            // 添加好友时可能会回调added方法两次
            if (!localUsers.containsKey(username)) {
                userDao.saveContact(user);
            }
            toAddUsers.put(username, user);
            //    }
            localUsers.putAll(toAddUsers);
            // 刷新ui
            // if (currentTabIndex == 1)
            // refresh();

        }
        /**
         * set head
         *
         * @param username
         * @return
         */
        FriendsUser setUserHead(String username) {
            FriendsUser user = new FriendsUser(username);
            // user.setUsername(username);
            String headerName = null;
            if (!TextUtils.isEmpty(user.getNick())) {
                headerName = user.getNick();
            } else {
                headerName = user.getUsername();
            }
            if (username.equals(Constants.NEW_FRIENDS_USERNAME)) {
                user.setHeader("");
            } else if (Character.isDigit(headerName.charAt(0))) {
                user.setHeader("#");
            } else {
                user.setHeader(
                        HanziToPinyin.getInstance().get(headerName.substring(0, 1))
                                .get(0).target.substring(0, 1).toUpperCase());
                char header = user.getHeader().toLowerCase().charAt(0);
                if (header < 'a' || header > 'z') {
                    user.setHeader("#");
                }
            }
            return user;
        }

        @Override
        public void onContactDeleted(final String username) {
            // 被删除
            Map<String, FriendsUser> localUsers = ((DemoHXSDKHelper) HXSDKHelper
                    .getInstance()).getContactList();
            //  for (String username : usernameList) {
            localUsers.remove(username);
            userDao.deleteContact(username);
            inviteMessgeDao.deleteMessage(username);
            //  }
            runOnUiThread(new Runnable() {
                public void run() {
                    // 如果正在与此用户的聊天页面
                    String st10 = getResources()
                            .getString(R.string.have_you_removed);
                    if (ChatActivity.activityInstance != null && username
                            .contains(ChatActivity.activityInstance
                                    .getToChatUsername())) {
                        Toast.makeText(LoginActivityV2.this,
                                ChatActivity.activityInstance
                                        .getToChatUsername() + st10,
                                1).show();
                        ChatActivity.activityInstance.finish();
                    }
                    // updateUnreadLabel();
                    // 刷新ui
                    // refresh();
                    // chatHistoryFragment.refresh();
                }
            });

        }

        @Override
        public void onContactInvited(String username, String reason) {

            // 接到邀请的消息，如果不处理(同意或拒绝)，掉线后，服务器会自动再发过来，所以客户端不需要重复提醒
            List<InviteMessage> msgs = inviteMessgeDao.getMessagesList();

            for (InviteMessage inviteMessage : msgs) {
                if (inviteMessage.getGroupId() == null
                        && inviteMessage.getFrom().equals(username)) {
                    inviteMessgeDao.deleteMessage(username);
                }
            }
            // 自己封装的javabean
            InviteMessage msg = new InviteMessage();
            msg.setFrom(username);
            msg.setTime(System.currentTimeMillis());
            msg.setReason(reason);
            Log.d(TAG, username + "请求加你为好友,reason: " + reason);
            // 设置相应status
            msg.setStatus(InviteMessage.InviteMesageStatus.BEINVITEED);
            notifyNewIviteMessage(msg, 0);

        }

        @Override
        public void onFriendRequestAccepted(String username) {
            List<InviteMessage> msgs = inviteMessgeDao.getMessagesList();
            for (InviteMessage inviteMessage : msgs) {
                if (inviteMessage.getFrom().equals(username)) {
                    return;
                }
            }
            // 自己封装的javabean
            InviteMessage msg = new InviteMessage();
            msg.setFrom(username);
            msg.setTime(System.currentTimeMillis());
            Log.d(TAG, username + "同意了你的好友请求");
            msg.setStatus(InviteMessage.InviteMesageStatus.BEAGREED);
            notifyNewIviteMessage(msg, 1);

        }

        @Override
        public void onFriendRequestDeclined(String username) {

            // 参考同意，被邀请实现此功能,demo未实现
            Log.d(username, username + "拒绝了你的好友请求");
        }

    }

    /** 显示通知栏点击跳转到指定Activity */
    public void showIntentActivityNotify(String message, int from) {
        mBuilder = new NotificationCompat.Builder(this);
        String mes = getString(R.string.new_message);
        // //在通知栏上点击此通知后自动清除此通知
        if (from == 0) {
            mes = getString(R.string.request_add_friend);
        } else if (from == 1) {
            mes = getString(R.string.agree_request_add_friend);
        } else if (from == 2) {
            mes = getString(R.string.request_group_chat);
        }
        mBuilder.setAutoCancel(true)
                // 点击后让通知将消失
                .setContentTitle(getResources().getString(R.string.app_name))
                .setContentText(message + mes).setTicker(message + mes)
                .setSmallIcon(R.drawable.lfy);
        // 点击的意图ACTION是跳转到Intent
        Intent resultIntent = new Intent(this, NewFriendsMsgActivity.class);
        resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(pendingIntent);
        mNotificationManager.notify(101, mBuilder.build());
    }

    /**
     * 保存提示新消息
     *
     * @param msg
     */
    private void notifyNewIviteMessage(InviteMessage msg, int id) {
        saveInviteMsg(msg);
        // 提示有新消息
        HXSDKHelper.getInstance().getNotifier().viberateAndPlayTone(null);
        showIntentActivityNotify(msg.getFrom(), id);
    }

    /**
     * 保存邀请等msg
     *
     * @param msg
     */
    private void saveInviteMsg(InviteMessage msg) {
        // 保存msg
        inviteMessgeDao.saveMessage(msg);
        // 未读数加1
        FriendsUser user = ((DemoHXSDKHelper) HXSDKHelper.getInstance())
                .getContactList().get(Constants.NEW_FRIENDS_USERNAME);
        if (user.getUnreadMsgCount() == 0)
            user.setUnreadMsgCount(user.getUnreadMsgCount() + 1);
    }
    private void initializeContacts() {
        Map<String, FriendsUser> userlist = new HashMap<String, FriendsUser>();
        // 新的朋友
        FriendsUser newFriends = new FriendsUser(Constants.NEW_FRIENDS_USERNAME);
        //   newFriends.setUsername(Constant.NEW_FRIENDS_USERNAME);
        String strChat = getResources()
                .getString(R.string.Application_and_notify);
        newFriends.setNickname(strChat);
        userlist.put(Constants.NEW_FRIENDS_USERNAME, newFriends);
        // 群聊
        FriendsUser groupUser = new FriendsUser(Constants.GROUP_USERNAME);
        String strGroup = getResources().getString(R.string.group_chat);
        //    groupUser.setUsername(Constant.GROUP_USERNAME);
        groupUser.setNickname(strGroup);
        groupUser.setHeader("");
        userlist.put(Constants.GROUP_USERNAME, groupUser);
        // 存入内存
        ((DemoHXSDKHelper) HXSDKHelper.getInstance()).setContactList(userlist);
        // 存入db
        UserDao dao = new UserDao(LoginActivityV2.this);
        List<FriendsUser> users = new ArrayList<FriendsUser>(userlist.values());
        dao.saveContactList(users);
    }
    /**
     * 授权。如果授权成功，则获取用户信息
     *
     * @param platform
     */
    private void login(final SHARE_MEDIA platform) {
        mShareAPI.doOauthVerify(this, platform,
                new UMAuthListener() {
                    @Override
                    public void onComplete(SHARE_MEDIA share_media, int i, final Map<String, String> map) {

                        LoginActivityV2.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                if (map.size() > 0) {
                                    getUserInfo(platform);
                                } else {
                                    Log.i(TAG, "获取信息失败...");
                                    Toast.makeText(LoginActivityV2.this, getString(R.string.Authority_fail),
                                            Toast.LENGTH_SHORT).show();
                                }
                            }
                        });

                    }

                    @Override
                    public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                        Toast.makeText(LoginActivityV2.this, getString(R.string.Authority_fail),
                                Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onCancel(SHARE_MEDIA share_media, int i) {
                        Toast.makeText(LoginActivityV2.this, getString(R.string.Authority_canel),
                                Toast.LENGTH_SHORT).show();
                    }
                }
        );
    }

    /**
     * 获取用户信息
     *
     * @param platform
     */
    private void getUserInfo(SHARE_MEDIA platform) {
        mShareAPI.getPlatformInfo(LoginActivityV2.this, platform,
                new UMAuthListener() {
                    @Override
                    public void onComplete(SHARE_MEDIA share_media, int status, Map<String, String> info) {
                        if (status == 2 & info != null) {
                            Log.i(TAG, info.toString());
                            thirdLogin(info);
                        } else {
                            Log.i(TAG, "获取信息失败...");
                        }
                    }

                    @Override
                    public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {

                    }

                    @Override
                    public void onCancel(SHARE_MEDIA share_media, int i) {

                    }
                }
        );
    }

    /**
     * 第三方登录数据解析
     */
    private void thirdLogin(Map<String, String> map) {
        if (!pd.isShowing()) {
            pd.setMessage(getString(R.string.wait));
            pd.show();
        }
        if (third_login == 1) {
            String s1 = map.get("headimgurl").toString().substring(0,
                    map.get("headimgurl").toString().lastIndexOf("0"));
            String avatarUrl = s1 + "132";
            String upSex = null;
            int sex = Integer.parseInt(map.get("sex"));
            if (sex == 1) {
                upSex = "m";
            } else if (sex == 2) {
                upSex = "f";
            } else {
                upSex = null;
            }
            ThirdLogin thirdLogin = new ThirdLogin();
            thirdLogin.setId(map.get("openid").toString());
            thirdLogin.setImagepath(avatarUrl);
            thirdLogin.setNickname(map.get("nickname").toString());
            thirdLogin.setType(third_login + "");
            thirdLogin.setSex(upSex);
            RegisterOtherUser(Constants.RegisterOtherUser_TEMP,
                    setObject(thirdLogin));
        } else if (third_login == 2) {
            /*StringBuilder sb = new StringBuilder();
            Set<String> keys = map.keySet();
            for(String key : keys){
                sb.append(key+"="+map.get(key).toString()+"\r\n");
            }*/
            String upSex = null;
            String result=map.get("result");
            JSONObject jsonObject=null;
            try {
                jsonObject=new JSONObject(result);
                String sex = jsonObject.getString("gender");
                if (sex.equals("m")) {
                    upSex = "m";
                } else if (sex.equals("f")) {
                    upSex = "f";
                } else {
                    upSex = null;
                }
                ThirdLogin thirdLogin = new ThirdLogin();
                String uid="";
                uid=jsonObject.get("id").toString();
                thirdLogin.setId(uid);
                thirdLogin.setImagepath(jsonObject.get("profile_image_url").toString());
                String name="";
                name=jsonObject.get("name").toString();
                thirdLogin.setNickname(name);
                thirdLogin.setType(third_login + "");
                thirdLogin.setSex(upSex);
                RegisterOtherUser(Constants.RegisterOtherUser_TEMP,
                        setObject(thirdLogin));
            } catch (JSONException e) {
                e.printStackTrace();
            }



        } else if (third_login == 3) {
            String upSex = null;
            String sex = map.get("gender").toString();
            if (sex.equals("男")) {
                upSex = "m";
            } else if (sex.equals("女")) {
                upSex = "f";
            } else {
                upSex = null;
            }
            ThirdLogin thirdLogin = new ThirdLogin();
            thirdLogin.setId(map.get("openid").toString());
            thirdLogin.setImagepath(map.get("profile_image_url").toString());
            thirdLogin.setNickname(map.get("screen_name").toString());
            thirdLogin.setType(third_login + "");
            thirdLogin.setSex(upSex);
            RegisterOtherUser(Constants.RegisterOtherUser_TEMP,
                    setObject(thirdLogin));
        } else {
            Toast.makeText(mContext, getString(R.string.third_parties_Authority_fail), Toast.LENGTH_SHORT).show();
        }
    }
    /**
     * 注册第三方登录
     *
     * @param registerOtherUserUrl
     * @param
     */
    private void RegisterOtherUser(String registerOtherUserUrl,
                                   String mThirdLogin) { //mThirdLogin {"id":"D6AAB059B43FE4F4AB74D2909EA34273","imagepath":"http://q.qlogo.cn/qqapp/1105000134/D6AAB059B43FE4F4AB74D2909EA34273/100","nickname":"水平线","sex":"m","type":"3"}
        Log.i(TAG,
                "<RegisterOtherUser>--<onResponse>--上传的JSon数据：  ThirdLoginJson = "
                        + mThirdLogin);
        isRegisterOtherUser = true;
        Type type = new TypeToken<BaseResult>() {
        }.getType();
        JsonListRequest<BaseResult> request = new JsonListRequest<BaseResult>(
                mContext, Request.Method.POST, registerOtherUserUrl, mThirdLogin, null,
                null, type, false, new Response.Listener<BaseResult>() {

            @Override
            public void onResponse(BaseResult arg0) {
                Log.i(TAG,
                        "<RegisterOtherUser>--<onResponse>--服务器返回的JSon数据：  arg0 = "
                                + arg0);
                int code = 1;
                String message = null;
                String data = null;
                message = arg0.getMessage();
                code = arg0.getCode();
                data = (String) arg0.getData();
                Log.i(TAG,
                        "<RegisterOtherUser>--<onResponse>--服务器返回的JSon数据：  message = "
                                + message);
                Log.i(TAG,
                        "<RegisterOtherUser>--<onResponse>--服务器返回的JSon数据：  code = "
                                + code);
                Log.i(TAG,
                        "<RegisterOtherUser>--<onResponse>--服务器返回的JSon数据：  data = "
                                + data);
                if (code == 0) {
                    if (data != null) {
                        currentUsername = data;  //这边赋值用户名
                        currentPassword = CommonUtils
                                .MD5(Constants.THIRDLOGINPASSWORD);//第三方通用登陆密码
                        if (!hasGetTokenJson) { //获取token
                            getUserToken();
                        }
                    }

                } else {
                    Toast.makeText(mContext, message, Toast.LENGTH_LONG)
                            .show();
                }
                isRegisterOtherUser = false;
                pd.dismiss();
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError arg0) {
                NetworkResponse response = arg0.networkResponse;
                if (response != null) {
                    try {
                        String json = new String(response.data,
                                HttpHeaderParser.parseCharset(
                                        response.headers));
                        Log.i(TAG,
                                "<getTokenRequest>--<onErrorResponse> -- json = "
                                        + json);
                        Log.i(TAG,
                                "<getTokenRequest>--<onErrorResponse> -- response.data = "
                                        + response.data);
                        Log.i(TAG,
                                "<getTokenRequest>--<onErrorResponse> -- response.headers = "
                                        + response.headers);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
                if (arg0 != null && arg0.toString().contains(
                        "com.android.volley.NoConnectionError")) {
                    Toast.makeText(mContext,
                            getString(R.string.network_unavailable),
                            Toast.LENGTH_SHORT).show();
                } else if (arg0 != null && arg0.toString()
                        .contains("com.android.volley.ServerError")) {
                    Toast.makeText(mContext,
                            getString(
                                    R.string.service_temporarily_unavailable),
                            Toast.LENGTH_SHORT).show();
                } else if (arg0 != null && arg0.toString()
                        .contains("com.android.volley.TimeoutError")) {
                    Toast.makeText(mContext,
                            getString(R.string.time_out_error),
                            Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(mContext,
                            getString(R.string.request_fail),
                            Toast.LENGTH_SHORT).show();
                }
                Log.i(TAG,
                        "<RegisterOtherUser>--<onErrorResponse>--服务器请求失败： arg0 = "
                                + arg0);
                Log.i(TAG,
                        "<RegisterOtherUser>--<onErrorResponse>--服务器请求失败： response = "
                                + response);
                isRegisterOtherUser = false;
                pd.dismiss();
            }

        });
        VolleyUtil.addRequest(request);
    }


    private void getUserToken(){
        hasGetTokenJson = true;
        NetHelper.getUserToken( LoginActivityV2.this, new NetUtils.NetCallBack<ServiceResult>() {
            @Override
            public void success(ServiceResult rspData) {
                TokenInfo info = (TokenInfo)rspData;
                if (info.getRetcode() == 0) {
                    String token =  info.getData();
                    Config.setUserToken(token);
                    loginChart();
                } else {
                    Toast.makeText(LoginActivityV2.this, rspData.getMessage(), Toast.LENGTH_SHORT).show();
                    pd.dismiss();
                }
                hasGetTokenJson = false;
            }

            @Override
            public void failed(String msg) {
                Toast.makeText(LoginActivityV2.this, msg, Toast.LENGTH_SHORT).show();
                hasGetTokenJson = false;
                pd.dismiss();
            }
        }, TokenInfo.class);
    }




    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mShareAPI.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ACTIVITY_RESULT_REGISTER) {
            if (resultCode == Activity.RESULT_OK) {
                if(data!= null && data.hasExtra("UserName"))
                    mUserNameEt.setText( data.getStringExtra("UserName"));
                if(data!= null && data.hasExtra("Password"))
                    mPasswordEt.setText( data.getStringExtra("Password"));
            }
        }
        if(requestCode == ACTIVITY_RESULT_FORGET_PASSWORD){
            if (resultCode == Activity.RESULT_OK) {
                if(data!= null && data.hasExtra("UserName"))
                    mUserNameEt.setText( data.getStringExtra("UserName"));
                if(data!= null && data.hasExtra("Password"))
                    mPasswordEt.setText( data.getStringExtra("Password"));
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        setStatusBar(R.color.common_bg);
    }
}
